package cc.rengu.redp.bizimpl.upmp.service.impl;

import cc.rengu.redp.bizimpl.enums.BizDataAuditStatusEnum;
import cc.rengu.redp.bizimpl.enums.BizDataStatusEnum;
import cc.rengu.redp.bizimpl.enums.BizOprEnum;
import cc.rengu.redp.bizimpl.enums.PageOptFlagEnum;
import cc.rengu.redp.bizimpl.igas.domain.PDstChannelCfg;
import cc.rengu.redp.bizimpl.igas.service.PDstChannelCfgService;
import cc.rengu.redp.bizimpl.upmp.common.BusinessContainer;
import cc.rengu.redp.bizimpl.upmp.dao.UpmpBPlatMchntInfoMapper;
import cc.rengu.redp.bizimpl.upmp.domain.*;
import cc.rengu.redp.bizimpl.upmp.service.*;
import cc.rengu.redp.bizimpl.upmp.vo.OperationResult;
import cc.rengu.redp.bizimpl.upmp.vo.UpmpUserInfoVO;
import cc.rengu.redp.bizimpl.utils.Common;
import cc.rengu.redp.bizimpl.utils.CommonUtils;
import cc.rengu.redp.bizimpl.utils.DateUtils;
import cc.rengu.redp.common.domain.QueryRequest;
import cc.rengu.redp.common.exception.RedpException;
import cc.rengu.redp.common.utils.SortUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author 刘玉亮.LL
 */
@Service
public class UpmpBPlatMchntInfoServiceImpl extends ServiceImpl<UpmpBPlatMchntInfoMapper, UpmpBPlatMchntInfo> implements IUpmpBPlatMchntInfoService {

    @Autowired
    private IUpmpSysParamService upmpSysParamService;
    @Autowired
    private IUpmpOrganizationService organizationService;

    @Autowired
    private IBBaseProdInfoService bBaseProdInfoService;
    @Autowired
    private PDstChannelCfgService pDstChannelCfgService;
    @Autowired
    private IBProdFeeInfoService bProdFeeInfoDao;
    @Autowired
    private IFeeInfoService feeInfoService;
    @Autowired
    private IWechatMchntInfoService bWechatMchntInfoService;
    @Autowired
    private IBizTmpService bizTmpService;
    @Autowired
    private IBizHisService bizHisService;
    @Autowired
    private IUpmpSysSeqService upmpSysSeqService;
    @Autowired
    private IProfitConfInfoService profitConfInfoService;
    @Autowired
    private IUpmpPrivilegeCheckService upmpPrivilegeCheckService;
    @Autowired
    private IndustryMapInfoService industryMapService;
    @Override
    public IPage<UpmpBPlatMchntInfo> findByPage(QueryRequest request, UpmpBPlatMchntInfo info) {
        try {
            LambdaQueryWrapper<UpmpBPlatMchntInfo> queryWrapper = new LambdaQueryWrapper<>();
            // 当前登录用户
            UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
            if (null != user && user.isAdmin()) {
                if (StringUtils.isBlank(info.getInstId())) {
                    info.setInstId(user.getInstId());
                }
            } else {
//                queryWrapper.in(UpmpBPlatMchntInfo::getCrtOrgId, Arrays.asList(GZIPUtils.uncompressToString(user.getUserOrgCodes()).split(",")));
            }
            queryWrapper.eq(UpmpBPlatMchntInfo::getInstId, info.getInstId());
            if (StringUtils.isNotBlank(info.getPlatMchntNo())) {
                queryWrapper.likeRight(UpmpBPlatMchntInfo::getPlatMchntNo, info.getPlatMchntNo());
            }
            if (StringUtils.isNotBlank(info.getPlatMchntName())) {
                queryWrapper.likeRight(UpmpBPlatMchntInfo::getPlatMchntName, info.getPlatMchntName());
            }
            if (StringUtils.isNotBlank(info.getManageInstId())) {
                queryWrapper.likeRight(UpmpBPlatMchntInfo::getManageInstId, info.getManageInstId());
            }
            if (StringUtils.isNotBlank(info.getArtifCertNo())) {
                queryWrapper.likeRight(UpmpBPlatMchntInfo::getArtifCertNo, info.getArtifCertNo());
            }
            Page<UpmpBPlatMchntInfo> page = new Page<>();
            SortUtil.handlePageSort(request, page, true);
            Page<UpmpBPlatMchntInfo> page1 = this.page(page, queryWrapper);
            for (UpmpBPlatMchntInfo p : page1.getRecords()) {
                UpmpOrganization orgByCode = organizationService.getOrgByCode(p.getManageInstId(), user.getInstId());
                if (null != orgByCode) {
                    p.setManageInstName(orgByCode.getOrgName());
                } else {
                    orgByCode = organizationService.getOrgByCode(p.getManageInstId(), p.getInstId());
                    if (null != orgByCode) {
                        p.setManageInstName(orgByCode.getOrgName());
                    }
                }
                // 微信进件状态
                WechatMchntInfo wechatMchntInfo = bWechatMchntInfoService.getBWechatMchntInfoByMchntNo(p.getPlatMchntNo(),p.getInstId());
                if (null != wechatMchntInfo) {
                    p.setWechatExpandStatus(wechatMchntInfo.getWechatEntryFlag());
                }
            }
            return page1;
        } catch (Exception e) {
            log.error("查询失败", e);
            return null;
        }
    }


    @Override
    public UpmpBPlatMchntInfo findOneByCode(String platMchntNo, String status, String instId) {
        LambdaQueryWrapper<UpmpBPlatMchntInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UpmpBPlatMchntInfo::getInstId, instId);
        queryWrapper.eq(UpmpBPlatMchntInfo::getPlatMchntNo, platMchntNo);
        queryWrapper.eq(UpmpBPlatMchntInfo::getPlatMchntStatus, status);
        return baseMapper.selectOne(queryWrapper);
    }

    /**
     * 根据基础产品配置出对应的分润配置
     */
    @Override
    public Map<BBaseProdInfo, List<ProfitConfInfo>> getProfitConfInfoList() throws RedpException {
        Map<BBaseProdInfo, List<ProfitConfInfo>> prodInfoProfitConfMap = new HashMap<>();

        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        UpmpOrganization org = organizationService.getOrgByCode(user.getOrgCode(), user.getInstId());
        //基础产品 某法人机构下出现重复产品类型的基础产品会引发异常
        List<BBaseProdInfo> bBaseProdInfos = bBaseProdInfoService.findByBaseProdCode(org.getInstId(), BusinessContainer.impStatus_01, "00");

        // 给基础产品分配分润配置
        for (BBaseProdInfo bBaseProdInfo : bBaseProdInfos) {
            if (!prodInfoProfitConfMap.containsKey(bBaseProdInfo)) {
                prodInfoProfitConfMap.put(bBaseProdInfo, new ArrayList<>());
            }
            // 基础产品编码 等于 07 或者 08 （07-微信支付 08-支付宝支付） 加载支付通道配置表数据
            if (bBaseProdInfo.getBaseProdCode().equals("07") ||
                    bBaseProdInfo.getBaseProdCode().equals("08")) {
                // 通道标识
                String dstChannelId = "";
                // 子业务类型 04-微信 05-支付宝
                String subProdType = "";
                if (bBaseProdInfo.getBaseProdCode().equals("07")) {
                    dstChannelId = "UPWX";
                    subProdType = "04";
                } else if (bBaseProdInfo.getBaseProdCode().equals("08")) {
                    dstChannelId = "UPAL";
                    subProdType = "05";
                }
                // 加载支付通道配置表数据，生成微信/支付宝 初始数据
                List<PDstChannelCfg> pDstChannelCfgList = pDstChannelCfgService.findPDstChannelCfgList(user.getInstId(), dstChannelId, "");
                if (null != pDstChannelCfgList) {
                    for (PDstChannelCfg pDstChannelCfg : pDstChannelCfgList) {
                        // 将通道配置信息 装换为 分润配置信息
                        ProfitConfInfo profitConfInfo = new ProfitConfInfo();
                        profitConfInfo.setId(CommonUtils.getUUID());
                        profitConfInfo.setBizProdCode(bBaseProdInfo.getBaseProdCode());
                        profitConfInfo.setSubProdType(subProdType);
                        profitConfInfo.setDstChannelType(pDstChannelCfg.getDstChannelType());
                        prodInfoProfitConfMap.get(bBaseProdInfo).add(profitConfInfo);
                    }
                }
            } else {
                // 获取产品费率 需要保证 每种费率类型唯一
                List<BProdFeeInfo> bProdFeeInfos = bProdFeeInfoDao.getBaseProdFeeList(user.getInstId(), "00", bBaseProdInfo.getBaseProdCode());

                for (BProdFeeInfo bProdFeeInfo : bProdFeeInfos) {
                    String feeType = bProdFeeInfo.getFeeType();
                    if (!feeType.equals("04") && !feeType.equals("05")) {

                        // 将通道配置信息 装换为 分润配置信息
                        ProfitConfInfo profitConfInfo = new ProfitConfInfo();
                        profitConfInfo.setId(CommonUtils.getUUID());
                        profitConfInfo.setBizProdCode(bBaseProdInfo.getBaseProdCode());
                        profitConfInfo.setSubProdType(bProdFeeInfo.getFeeType());
                        profitConfInfo.setDstChannelType("");
                        prodInfoProfitConfMap.get(bBaseProdInfo).add(profitConfInfo);
                    }
                }
            }
            if (bBaseProdInfo.getBaseProdCode().equals("02") || bBaseProdInfo.getBaseProdCode().equals("03") || bBaseProdInfo.getBaseProdCode().equals("04")) {
                List<PDstChannelCfg> pDstChannelCfgList = new ArrayList<>();
                String[] dstChannelId = new String[]{"UPWX", "UPAL"};
                // 子业务类型 04-微信 05-支付宝
                String subProdType = "";
                for (int i = 0; i < dstChannelId.length; i++) {
                    pDstChannelCfgList = pDstChannelCfgService.findPDstChannelCfgList(user.getInstId(), dstChannelId[i], "");
                    if (dstChannelId[i].equals("UPWX")) {
                        subProdType = "04";
                    } else {
                        subProdType = "05";
                    }
                    if (null != pDstChannelCfgList) {
                        for (PDstChannelCfg pDstChannelCfg : pDstChannelCfgList) {

                            // 将通道配置信息 装换为 分润配置信息
                            ProfitConfInfo profitConfInfo = new ProfitConfInfo();
                            profitConfInfo.setId(CommonUtils.getUUID());
                            profitConfInfo.setBizProdCode(bBaseProdInfo.getBaseProdCode());
                            profitConfInfo.setSubProdType(subProdType);
                            profitConfInfo.setDstChannelType(pDstChannelCfg.getDstChannelType());
                            prodInfoProfitConfMap.get(bBaseProdInfo).add(profitConfInfo);
                        }
                    }
                }
            }
        }


        return prodInfoProfitConfMap;
    }

    @Override
    public String genProfitPrimaryKey(ProfitConfInfo profitConfInfo) {
        StringBuilder result = new StringBuilder();
        // 多法人总行机构标识(inst_id) + 分润类型(profit_type) + 关联业务编码(biz_code) + 业务产品代码(biz_prod_code) + 子业务类型(sub_prod_type) +
        // 通道类型(dst_channel_type)+分润模式(profit_input_mode)+费率生效日期(profit_effective_date)+固定金额分段序号(profit_fixed_index)
        if (null != profitConfInfo) {
            result.append(profitConfInfo.getInstId());
            result.append(profitConfInfo.getProfitType());
            result.append(profitConfInfo.getBizCode());
            result.append(profitConfInfo.getBizProdCode());
            result.append(profitConfInfo.getSubProdType());
            result.append(profitConfInfo.getDstChannelType());
            result.append(profitConfInfo.getProfitInputMode());
            result.append(profitConfInfo.getProfitEffectiveDate());
            result.append(profitConfInfo.getProfitFixedIndex());
        }
        return result.toString();
    }
    private List<ProfitConfInfo> findProfitConfInfoList(UpmpBPlatMchntInfo platMchntInfo) throws RedpException {
        List<ProfitConfInfo> list = new ArrayList<ProfitConfInfo>();

        // 不参与分润
        if (platMchntInfo.getIsProfitFlag().equals("0")) {
            return list;
        }

        // 全产品分润 保存时是将每个基础产品的分润都配置成这种分润规则
        if (platMchntInfo.getProfitRule().equals("00")) {
            // 获取全部产品分润配置
            Map<BBaseProdInfo, List<ProfitConfInfo>> profitConfInfoListMap = getProfitConfInfoList();
            List<ProfitConfInfo> profitConfInfos = new ArrayList<>();
            for (List<ProfitConfInfo> pc : profitConfInfoListMap.values()) {
                profitConfInfos.addAll(pc);
            }
            //
            for (ProfitConfInfo profitConfInfo : profitConfInfos) {
                // 如果选择了需要向微信进件 且 微信通道不为空 且 基础产品代码为 07-微信。根据微信通道筛选可用通道
                if (platMchntInfo.getIsWechatEntryFlag().equals("1") &&
                        StringUtils.isNotBlank(platMchntInfo.getChannelType()) &&
                        profitConfInfo.getBizProdCode().equals("07")) {
                    // 非选中的微信通道，不处理
                    if (!platMchntInfo.getChannelType().equals(profitConfInfo.getDstChannelType())) {
                        continue;
                    }
                }
                // 如果固定金额 且 固定金额费率模板不为空；加载费率模板数据进行填充
                if (platMchntInfo.getProfitInputModeALL().equals("01") &&
                        StringUtils.isNotBlank(platMchntInfo.getProfitFixedIndexALL())) {
                    //查询费率模板，是否存在多条费率，如果是保存多条
                    List<FeeInfo> feeInfos = feeInfoService.findallBypCalType(platMchntInfo.getProfitFixedIndexALL(), platMchntInfo.getInstId());
                    for (FeeInfo feeInfo : feeInfos) {
                        ProfitConfInfo profitConfInfoTarget = new ProfitConfInfo();
                        BeanUtils.copyProperties(profitConfInfo, profitConfInfoTarget);

                        profitConfInfoTarget.setProfitInputMode(platMchntInfo.getProfitInputModeALL());

                        profitConfInfoTarget.setProfitFixedIndex(feeInfo.getPSeqNo());
                        profitConfInfoTarget.setProfitFixedStart(Common.isBlank(feeInfo.getPStartValue())?"":feeInfo.getPStartValue().toString());
                        profitConfInfoTarget.setProfitFixedEnd(Common.isBlank(feeInfo.getPEndValue())?"":feeInfo.getPEndValue().toString());
                        profitConfInfoTarget.setProfitFixedAmt(Common.isBlank(feeInfo.getPValue())?"":feeInfo.getPValue().toString());

                        profitConfInfoTarget.setProfitScale(platMchntInfo.getProfitScaleALL());
                        profitConfInfoTarget.setProfitCappingAmt(platMchntInfo.getProfitCappingAmtALL());

                        profitConfInfoTarget.setCostCappingAmt(platMchntInfo.getCostCappingAmtALL());
                        profitConfInfoTarget.setCostFeeRate(platMchntInfo.getCostFeeRateALL());

                        profitConfInfoTarget.setRemark1(feeInfo.getFeeCd() + "," + feeInfo.getFeeName());
                        list.add(profitConfInfoTarget);
                    }
                } else {
                    profitConfInfo.setProfitFixedIndex(0);

                    profitConfInfo.setProfitInputMode(platMchntInfo.getProfitInputModeALL());
                    profitConfInfo.setProfitFixedAmt(platMchntInfo.getProfitFixedAmtALL());
                    profitConfInfo.setProfitScale(platMchntInfo.getProfitScaleALL());
                    profitConfInfo.setProfitCappingAmt(platMchntInfo.getProfitCappingAmtALL());
                    profitConfInfo.setCostCappingAmt(platMchntInfo.getCostCappingAmtALL());
                    profitConfInfo.setCostFeeRate(platMchntInfo.getCostFeeRateALL());

                    list.add(profitConfInfo);
                }
            }
            // 全产品统一分润只在新增时显示
            platMchntInfo.setProfitRule("01");
        } else if (platMchntInfo.getProfitRule().equals("01")) {
            //业务产品分润
            List<ProfitConfInfo> profitConfInfos = JSON.parseArray(platMchntInfo.getProfitConfInfoList(), ProfitConfInfo.class);

            for (ProfitConfInfo profitConfInfo : profitConfInfos) {
                // 如果选择了，需要向微信进件 且 微信通道不为空 且 基础产品代码为 07-微信。根据微信通道筛选可用通道
                if (platMchntInfo.getIsWechatEntryFlag().equals("1") &&
                        StringUtils.isNotBlank(platMchntInfo.getChannelType()) &&
                        profitConfInfo.getBizProdCode().equals("07")) {
                    // 非选中的微信通道，不处理
                    if (!platMchntInfo.getChannelType().equals(profitConfInfo.getDstChannelType())) {
                        continue;
                    }
                }
                //如果固定金额 固定金额费率模板不为空
                if (profitConfInfo.getProfitInputMode().equals("01") &&
                        StringUtils.isNotBlank(profitConfInfo.getProfitFixedIndexS())) {
                    //查询费率模板，是否存在多条费率，如果是保存多条
                    List<FeeInfo> feeInfos = feeInfoService.findallBypCalType(profitConfInfo.getProfitFixedIndexS(), platMchntInfo.getInstId());
                    for (FeeInfo f : feeInfos) {
                        ProfitConfInfo ALL = new ProfitConfInfo();

                        ALL.setProfitInputMode(profitConfInfo.getProfitInputMode());

                        ALL.setProfitFixedIndex(f.getPSeqNo());
                        ALL.setProfitFixedStart(Common.isBlank(f.getPStartValue())?"":f.getPStartValue().toString());
                        ALL.setProfitFixedEnd(Common.isBlank(f.getPEndValue())?"":f.getPEndValue().toString());
                        ALL.setProfitFixedAmt(Common.isBlank(f.getPValue())?"":f.getPValue().toString());

                        ALL.setDstChannelType(profitConfInfo.getDstChannelType());
                        ALL.setBizProdCode(profitConfInfo.getBizProdCode());
                        ALL.setSubProdType(profitConfInfo.getSubProdType());
                        ALL.setRemark1(f.getFeeCd() + "," + f.getFeeName());
                        list.add(ALL);
                    }
                } else {
                    ProfitConfInfo ALL = new ProfitConfInfo();

                    ALL.setProfitFixedIndex(0);

                    ALL.setProfitInputMode(profitConfInfo.getProfitInputMode());
                    ALL.setProfitFixedAmt(profitConfInfo.getProfitFixedAmt());
                    ALL.setProfitScale(profitConfInfo.getProfitScale());
                    ALL.setProfitCappingAmt(profitConfInfo.getProfitCappingAmt());
                    ALL.setCostCappingAmt(profitConfInfo.getCostCappingAmt());
                    ALL.setCostFeeRate(profitConfInfo.getCostFeeRate());

                    ALL.setDstChannelType(profitConfInfo.getDstChannelType());
                    ALL.setBizProdCode(profitConfInfo.getBizProdCode());
                    ALL.setSubProdType(profitConfInfo.getSubProdType());
                    list.add(ALL);
                }
            }
        }
        return list;
    }
    /**
     * 系统自动生成代理商编码：AG + 8位顺序编码
     *
     * @return
     */
    public String generateCode(String instId) {
        // 获取渠道ID：固定20
        String channelId = CommonUtils.getChannelId(upmpSysParamService,instId);
        // 代理商编码前缀：AG
        String prefix = BusinessContainer.PlatMchntNo_PREFIX;
        // 自动生成一级代码
        String paramCode = BusinessContainer.COMM_PARAM_CODE;
        // 生成序列号
        String seqNum =  upmpSysSeqService.updateParamValue(paramCode, "PLAT_MCHNT_INFO", channelId);

        // 代理商编码
        String result = prefix + String.format("%08d", Integer.parseInt(seqNum));
        return result;
    }
    @Override
    @Transactional(value = "transactionManager")
    public OperationResult saveData(String menuId, String oprMenuName, UpmpBPlatMchntInfo entity, HttpServletRequest request, String webNextUrl) throws RedpException {
        java.util.Map<String, Object> result = com.google.common.collect.Maps.newHashMap();
        String optFlag = request.getParameter("optFlag") == null ? "" : request.getParameter("optFlag");
        String lastUpddt = DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS");
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        String instId = entity.getInstId();
        String crtOrgId = "";
        entity.setSettleType(" ");
        entity.setSettleAcctNo(" ");
        entity.setSettleAcctType(" ");
        entity.setSettleAcctName(" ");
        entity.setAcctOpenBankNo(" ");
        entity.setAcctOpenBankName(" ");
        if (optFlag.equals("add") && user.isAdmin()) {
            if (StringUtils.isEmpty(instId)) {
                log.error("保存数据时请先选择法人行!");
                return OperationResult.buildFailureResult("保存数据时请先选择法人行!");
            } else {
                UpmpOrganization headOrg = organizationService.getHeadOrgByCode(instId);
                crtOrgId = (headOrg == null ? user.getOrgCode() : headOrg.getOrgCode());
            }
        } else {
            instId = (instId == null ? user.getInstId() : instId);
            crtOrgId = (entity.getCrtOrgId() == null ? user.getOrgCode() : entity.getCrtOrgId());
        }
        UpmpOrganization org = organizationService.getOrgByCode(crtOrgId, instId);

        entity.setLastOprId(user.getId());
        entity.setLastUpdateTime(lastUpddt);

        List<ProfitConfInfo> saveProfit;
        List<ProfitConfInfo> expProfit;

        UpmpBPlatMchntInfo oldEntity = null;
        if (!PageOptFlagEnum.OPT_FLAG_ADD.getType().equals(optFlag)) {
            oldEntity = this.getById(entity.getId());
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String nowDate = sdf.format(new Date());

        // “新增”或“修改”
        if (optFlag.equals("add") || optFlag.equals("upd")) {
            if (optFlag.equals("add")) {
                entity.setId(null);
                entity.setPlatMchntNo(generateCode(entity.getPlatMchntNo()));
                entity.setOprId(user.getId());
                entity.setCrtOrgId(org.getOrgCode());
                entity.setCreateTime(lastUpddt);

                // 分润信息处理
                saveProfit = findProfitConfInfoList(entity);

                //获取审核信息
                UpmpPrivilegeCheck privilegeCheck = upmpPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(user.getInstId(), "platMchnt:add");
                if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                    //需要审核
                    entity.setAuditStatus(BusinessContainer.status_01);
                    entity.setPlatMchntStatus(BusinessContainer.agentStatus_00);
                    //保存entity profitconfList TMP
                    this.saveOrUpdate(entity);
                    entity.setProfitConfInfoList(null);
                    bizTmpService.saveBizTmpDtl(entity, user, org.getInstId(), BizOprEnum.OPR_ADD.getType(), lastUpddt,
                            menuId, oprMenuName, entity.getPlatMchntStatus(), entity.getAuditStatus(), entity.getId(), webNextUrl, "N", "", null, null, null);

                    //直接保存新的分润信息
                    for (ProfitConfInfo profitConfInfo : saveProfit) {
                        profitConfInfo.setInstId(org.getInstId());
                        profitConfInfo.setProfitType("02");
                        profitConfInfo.setBizCode(entity.getPlatMchntNo());
                        profitConfInfo.setProfitEffectiveDate(nowDate);
                        profitConfInfo.setProfitExpiryDate(BusinessContainer.doomsday);
                        profitConfInfo.setProfitStatus(entity.getPlatMchntStatus());
                        profitConfInfo.setAuditStatus(entity.getAuditStatus());
                        profitConfInfo.setLastAuditId(user.getId());
                        profitConfInfo.setLastAuditTime(lastUpddt);
                        // 生成 分润配置唯一标识
                        profitConfInfo.setProfitPrimaryKey(genProfitPrimaryKey(profitConfInfo));
                        // 分润配置信息保存正式表
                        profitConfInfoService.save(profitConfInfo);
                        // 分润配置明细保存临时表
                        bizTmpService.saveBizTmpDtl(profitConfInfo, user, org.getInstId(), BizOprEnum.OPR_ADD.getType(), lastUpddt,
                                menuId, oprMenuName, entity.getPlatMchntStatus(), entity.getAuditStatus(), profitConfInfo.getId(), webNextUrl, "Y", entity.getId(), null, null, null);
                    }
                    // 选择了需要向微信进件，保存信息到微信商户信息表
                    if ("1".equals(entity.getIsWechatEntryFlag())) {
                        WechatMchntInfo wechatMchntInfo = getBWechatMchntInfo(entity);
                        bWechatMchntInfoService.save(wechatMchntInfo);
                        // 微信商户信息明细保存临时表
                        bizTmpService.saveBizTmpDtl(wechatMchntInfo, user, org.getInstId(), BizOprEnum.OPR_ADD.getType(), lastUpddt,
                                menuId, oprMenuName, entity.getPlatMchntStatus(), wechatMchntInfo.getAuditStatus(), wechatMchntInfo.getId(), webNextUrl, "Y", entity.getId(), null, null, null);
                    }
                } else {
                    entity.setAuditStatus(BusinessContainer.status_02);
                    entity.setPlatMchntStatus(BusinessContainer.agentStatus_01);
                    //保存 entity profitconfList His
                    this.saveOrUpdate(entity);

                    bizHisService.saveBizHisNew(entity, entity, user, org.getInstId(), BizOprEnum.OPR_ADD.getType(), lastUpddt, menuId, oprMenuName, entity.getId(), null, null, null);

                    //直接保存新的分润信息
                    for (ProfitConfInfo profitConfInfo : saveProfit) {
                        profitConfInfo.setInstId(org.getInstId());
                        profitConfInfo.setProfitType("02");
                        profitConfInfo.setBizCode(entity.getPlatMchntNo());
                        profitConfInfo.setProfitEffectiveDate(nowDate);
                        profitConfInfo.setProfitExpiryDate(BusinessContainer.doomsday);
                        profitConfInfo.setProfitStatus(entity.getPlatMchntStatus());
                        profitConfInfo.setAuditStatus(entity.getAuditStatus());
                        profitConfInfo.setLastAuditId(user.getId());
                        profitConfInfo.setLastAuditTime(lastUpddt);
                        // 生成 分润配置唯一标识
                        profitConfInfo.setProfitPrimaryKey(genProfitPrimaryKey(profitConfInfo));

                        // 分润配置信息保存正式表
                        profitConfInfoService.save(profitConfInfo);
                        // 分润配置明细保存历史表
                        bizHisService.saveBizHisNew(profitConfInfo, profitConfInfo, user, org.getInstId(), BizOprEnum.OPR_ADD.getType(), lastUpddt, menuId, oprMenuName, profitConfInfo.getId(), null, null, null);
                    }
                    // 选择了需要向微信进件，保存信息到微信商户信息表
                    if ("1".equals(entity.getIsWechatEntryFlag())) {
                        WechatMchntInfo wechatMchntInfo = getBWechatMchntInfo(entity);
                        bWechatMchntInfoService.save(wechatMchntInfo);
                        // 微信商户信息明细保存历史
                        bizHisService.saveBizHisNew(wechatMchntInfo, wechatMchntInfo, user, org.getInstId(), BizOprEnum.OPR_ADD.getType(), lastUpddt, menuId, oprMenuName, wechatMchntInfo.getId(), null, null, null);
                        //调用第三方进件接口进件
                        if (null != wechatMchntInfo) {
                            result.put("mchntNo", entity.getPlatMchntNo());
                            result.put("channelType", entity.getChannelType());
                            result.put("appId", wechatMchntInfo.getAppId());
                            result.put("miniAppId", wechatMchntInfo.getMiniAppId());
                            result.put("oprType", "0");
                            /*log.info("开始第三方进件！");
                            InstMchntRegisterRequest req = new InstMchntRegisterRequest();
                            req.setMchntNo(entity.getPlatMchntNo());
                            String oprType = "0";
                            req.setChannelType(entity.getChannelType());
                            req.setChannelFlag("01");
                            req.setWechatAppid(wechatMchntInfo.getAppId());
                            req.setWechatMiniAppid(wechatMchntInfo.getMiniAppId());
                            req.setUserId(user.getId());
                            req.setMchntBizFlag("01");
                            req.setOprType(oprType);
                            bMchntBaseInfoService.thirdEntry(entity.getInstId(), req, bompThirdMchntEntryService, bMchntBaseInfoService.genMerOrder(user.getInstId()));*/
                        }
                    }
                }
            } else if (optFlag.equals("upd")) {
                UpmpBPlatMchntInfo dbPlatMchntInfo = this.getById(entity.getId());
                //获取审核信息
                UpmpPrivilegeCheck privilegeCheck = upmpPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(user.getInstId(), "platMchnt:edit");
                if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                    // 1、修改的数据存入临时表，正式表仅修改状态
                    dbPlatMchntInfo.setAuditStatus(BusinessContainer.status_41);
                    dbPlatMchntInfo.setLastOprId(user.getId());
                    dbPlatMchntInfo.setLastUpdateTime(lastUpddt);
                    this.saveOrUpdate(dbPlatMchntInfo);

                    // 1.1、入临时表
                    entity.setAuditStatus(dbPlatMchntInfo.getAuditStatus());
                    entity.setLastOprId(dbPlatMchntInfo.getLastOprId());
                    entity.setLastUpdateTime(dbPlatMchntInfo.getLastUpdateTime());
                    saveProfit = findProfitConfInfoList(entity);
                    entity.setProfitConfInfoList(null);
                    bizTmpService.saveBizTmpDtl(entity, user, org.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt,
                            menuId, oprMenuName, dbPlatMchntInfo.getPlatMchntStatus(), dbPlatMchntInfo.getAuditStatus(), dbPlatMchntInfo.getId(), webNextUrl, "N", "", null, null, null);
                    // 2、获取分润配置正式表数据，并且修改状态； 获取临时表分润配置信息，进行数据的修改
                    expProfit = profitConfInfoService.findByBizCode(entity.getPlatMchntNo());
                    for (ProfitConfInfo profitConfInfo : expProfit) {
                        profitConfInfo.setAuditStatus(dbPlatMchntInfo.getAuditStatus());
                        profitConfInfo.setLastOprId(user.getId());
                        profitConfInfo.setLastUpdateTime(lastUpddt);
                        profitConfInfoService.save(profitConfInfo);
                    }
                    List<BizTmp> bizTmpByMasterKey = bizTmpService.getBizTmpByMasterKey(entity.getInstId(), entity.getId());
                    List<BizTmp> deleteProfitConfBizTmps = new ArrayList<>();
                    for (BizTmp bizTmp : bizTmpByMasterKey) {
                        // 筛选分润配置信息
                        if ("t_b_profit_conf_info".equals(bizTmp.getOprTableEname().toLowerCase())) {
                            deleteProfitConfBizTmps.add(bizTmp);
                        }
                    }
                    // 2.1、先删除临时表 分润配置信息数据
                    bizTmpService.delete(deleteProfitConfBizTmps);
                    // 2.2、将修改后分润配置信息保存到临时表

                    for (ProfitConfInfo profitConfInfo : saveProfit) {
                        String uuid = CommonUtils.getUUID();
                        profitConfInfo.setId(uuid);
                        profitConfInfo.setInstId(dbPlatMchntInfo.getInstId());
                        profitConfInfo.setProfitType("02");
                        profitConfInfo.setBizCode(dbPlatMchntInfo.getPlatMchntNo());
                        profitConfInfo.setProfitEffectiveDate(nowDate);
                        profitConfInfo.setProfitExpiryDate(BusinessContainer.doomsday);
                        profitConfInfo.setProfitStatus(dbPlatMchntInfo.getPlatMchntStatus());
                        profitConfInfo.setAuditStatus(dbPlatMchntInfo.getAuditStatus());
                        profitConfInfo.setLastAuditId(user.getId());
                        profitConfInfo.setLastAuditTime(lastUpddt);
                        // 生成 分润配置唯一标识
                        profitConfInfo.setProfitPrimaryKey(genProfitPrimaryKey(profitConfInfo));

                        bizTmpService.saveBizTmpDtl(profitConfInfo, user, org.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt,
                                menuId, oprMenuName, dbPlatMchntInfo.getPlatMchntStatus(), profitConfInfo.getAuditStatus(), profitConfInfo.getId(), webNextUrl, "Y", dbPlatMchntInfo.getId(), null, null, null);
                    }
                    // 选择了需要向微信进件，修改微信商户表的临时表数据。反之删除数据
                    if ("1".equals(entity.getIsWechatEntryFlag())) {
                        // 3、获取微信商户正式表数据，并且修改状态；
                        WechatMchntInfo dbBWechatMchntInfo = bWechatMchntInfoService.getBWechatMchntInfoByMchntNo(entity.getPlatMchntNo(),entity.getInstId());
                        WechatMchntInfo wechatMchntInfoTem = new WechatMchntInfo();
                        if (null == dbBWechatMchntInfo) {
                            // 新增数据时选择不需要微信进件，修改数据时改为需要微信进件
                            dbBWechatMchntInfo = getBWechatMchntInfo(entity);
                            //dbBWechatMchntInfo.setId((String) gen.generate(null, null));
                            bWechatMchntInfoService.save(dbBWechatMchntInfo);
                            wechatMchntInfoTem.setId(dbBWechatMchntInfo.getId());
                        } else {
                            dbBWechatMchntInfo.setAuditStatus(dbPlatMchntInfo.getAuditStatus());
                            dbBWechatMchntInfo.setLastOprId(user.getId());
                            dbBWechatMchntInfo.setLastUpdateTime(lastUpddt);
                            bWechatMchntInfoService.save(dbBWechatMchntInfo);
                            // 微信商户临时表数据
                            List<WechatMchntInfo> bWechatMchntInfos = bizTmpService.getBizTmpByInstIdAndMasterKeyAndEname(entity.getInstId(), WechatMchntInfo.class, entity.getId());
                            if (null != bWechatMchntInfos && bWechatMchntInfos.size() > 0) {
                                wechatMchntInfoTem = bWechatMchntInfos.get(0);
                            }
                        }
                        // 3.1、获取修改后的微信商户信息，进行数据的修改
                        WechatMchntInfo wechatMchntInfoNew = getBWechatMchntInfo(entity);
                        wechatMchntInfoNew.setId(dbBWechatMchntInfo.getId());
                        wechatMchntInfoNew.setAuditStatus(dbPlatMchntInfo.getAuditStatus());
                        wechatMchntInfoNew.setLastOprId(user.getId());
                        wechatMchntInfoNew.setLastUpdateTime(lastUpddt);

                        BeanUtils.copyProperties(wechatMchntInfoNew, wechatMchntInfoTem);
                        bizTmpService.saveBizTmpDtl(wechatMchntInfoTem, user, org.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt,
                                menuId, oprMenuName, dbPlatMchntInfo.getPlatMchntStatus(), wechatMchntInfoTem.getAuditStatus(), wechatMchntInfoTem.getId(), webNextUrl, "Y", dbPlatMchntInfo.getId(), null, null, null);
                    } else {
                        // 如果修改成无需进件，则删除临时表的微信商户数据
                        WechatMchntInfo dbBWechatMchntInfo = bWechatMchntInfoService.getBWechatMchntInfoByMchntNo(entity.getPlatMchntNo(),entity.getInstId());
                        if (null != dbBWechatMchntInfo) {
                            BizTmp bizTmp = bizTmpService.getById(dbBWechatMchntInfo.getId());
                            bizTmpService.getBaseMapper().deleteById(bizTmp.getRealId());
                        }
                    }
                } else {
                    // 保存正式表 profitconfList His
                    entity.setAuditStatus(BusinessContainer.status_42);
                    entity.setPlatMchntStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
                    this.saveOrUpdate(entity);
                    saveProfit = findProfitConfInfoList(entity);
                    entity.setProfitConfInfoList(null);
                    // 保存历史表
                    bizHisService.saveBizHisNew(entity, oldEntity, user, org.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt,
                            menuId, oprMenuName, entity.getId(), null, null, null);

                    // 选择了需要向微信进件，修改微信商户表的临时表数据。反之删除数据
                    if ("1".equals(entity.getIsWechatEntryFlag())) {
                        // 1、获取微信商户正式表数据，并且修改状态；
                        WechatMchntInfo dbBWechatMchntInfo = bWechatMchntInfoService.getBWechatMchntInfoByMchntNo(entity.getPlatMchntNo(),entity.getInstId());
                        if (null == dbBWechatMchntInfo) {
                            // 新增数据时选择不需要微信进件，修改数据时改为需要微信进件，则需要新增微信商户表数据
                            dbBWechatMchntInfo = getBWechatMchntInfo(entity);
                            bWechatMchntInfoService.save(dbBWechatMchntInfo);

                            bizHisService.saveBizHisNew(dbBWechatMchntInfo, dbBWechatMchntInfo, user, org.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt,
                                    menuId, oprMenuName, dbBWechatMchntInfo.getId(), null, null, null);
                            //调用第三方进件接口进件
                            result.put("mchntNo", entity.getPlatMchntNo());
                            result.put("channelType", entity.getChannelType());
                            result.put("appId", dbBWechatMchntInfo.getAppId());
                            result.put("miniAppId", dbBWechatMchntInfo.getMiniAppId());
                            result.put("oprType", "0");
                           /* log.info("开始第三方进件！");
                            InstMchntRegisterRequest req = new InstMchntRegisterRequest();
                            req.setMchntNo(entity.getPlatMchntNo());
                            String oprType = "0";
                            req.setChannelType(entity.getChannelType());
                            req.setChannelFlag("01");
                            req.setWechatAppid(dbBWechatMchntInfo.getAppId());
                            req.setWechatMiniAppid(dbBWechatMchntInfo.getMiniAppId());
                            req.setUserId(user.getId());
                            req.setMchntBizFlag("01");
                            req.setOprType(oprType);
                            bMchntBaseInfoService.thirdEntry(entity.getInstId(), req, bompThirdMchntEntryService, bMchntBaseInfoService.genMerOrder(user.getInstId()));*/
                        } else {
                            WechatMchntInfo wechatMchntInfoNew = getBWechatMchntInfo(entity);
                            wechatMchntInfoNew.setId(dbBWechatMchntInfo.getId());
                            wechatMchntInfoNew.setAuditStatus(dbPlatMchntInfo.getAuditStatus());
                            wechatMchntInfoNew.setLastOprId(user.getId());
                            wechatMchntInfoNew.setLastUpdateTime(lastUpddt);
                            bWechatMchntInfoService.save(wechatMchntInfoNew);

                            bizHisService.saveBizHisNew(wechatMchntInfoNew, dbBWechatMchntInfo, user, org.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt,
                                    menuId, oprMenuName, wechatMchntInfoNew.getId(), null, null, null);
                            //调用第三方进件接口进件
                           /* log.info("开始第三方进件！");
                            InstMchntRegisterRequest req = new InstMchntRegisterRequest();
                            req.setMchntNo(entity.getPlatMchntNo());*/
                            String oprType = "1";
                            //进件状态为空或者失败，且微信商户号为空时是入驻
                            if ((Common.isBlank(dbBWechatMchntInfo.getWechatEntryFlag()) || "02".equals(dbBWechatMchntInfo.getWechatEntryFlag())) && Common.isBlank(dbBWechatMchntInfo.getWechatMchntNo())) {
                                oprType = "0";
                            }
                           /* req.setChannelType(entity.getChannelType());
                            req.setChannelFlag("01");
                            req.setWechatAppid(wechatMchntInfoNew.getAppId());
                            req.setWechatMiniAppid(wechatMchntInfoNew.getMiniAppId());
                            req.setUserId(user.getId());
                            req.setMchntBizFlag("01");
                            req.setOprType(oprType);
                            bMchntBaseInfoService.thirdEntry(entity.getInstId(), req, bompThirdMchntEntryService, bMchntBaseInfoService.genMerOrder(user.getInstId()));*/
                            result.put("mchntNo", entity.getPlatMchntNo());
                            result.put("channelType", entity.getChannelType());
                            result.put("appId", wechatMchntInfoNew.getAppId());
                            result.put("miniAppId", wechatMchntInfoNew.getMiniAppId());
                            result.put("oprType", oprType);
                        }
                    } else {
                        // 如果修改成无需进件，则删除临时表的微信商户数据
                        WechatMchntInfo dbBWechatMchntInfo = bWechatMchntInfoService.getBWechatMchntInfoByMchntNo(entity.getPlatMchntNo(),entity.getInstId());
                        if (null != dbBWechatMchntInfo) {
                            bWechatMchntInfoService.getBaseMapper().deleteById(dbBWechatMchntInfo.getId());

                            bizHisService.saveBizHisNew(dbBWechatMchntInfo, dbBWechatMchntInfo, user, org.getInstId(), BizOprEnum.OPR_DELETE.getType(), lastUpddt,
                                    menuId, oprMenuName, dbBWechatMchntInfo.getId(), null, null, null);
                        }
                    }
                    /* 前端分润配置无法赋值id,无法比对出哪些是新增，删除，修改
                    // 2、获取分润配置正式表数据，与新修改的配置信息做比较。
                    List<ProfitConfInfo> oldProfitConfInfos = profitConfInfoService.findByBizCode(entity.getPlatMchntNo());
                    List<ProfitConfInfo> newProfitConfInfos = findProfitConfInfoList(entity);
                    for (ProfitConfInfo profitConfInfo : newProfitConfInfos) {
                        profitConfInfo.setInstId(dbPlatMchntInfo.getInstId());
                        profitConfInfo.setProfitType("02");
                        profitConfInfo.setBizCode(dbPlatMchntInfo.getPlatMchntNo());
                        profitConfInfo.setProfitEffectiveDate(nowDate);
                        profitConfInfo.setProfitExpiryDate(BusinessContainer.doomsday);
                        profitConfInfo.setProfitStatus(dbPlatMchntInfo.getPlatMchntStatus());
                        profitConfInfo.setAuditStatus(dbPlatMchntInfo.getAuditStatus());
                        profitConfInfo.setLastAuditId(user.getId());
                        profitConfInfo.setLastAuditTime(lastUpddt);
                        // 生成 分润配置唯一标识
                        profitConfInfo.setProfitPrimaryKey(genProfitPrimaryKey(profitConfInfo));
                    }
                    // 修改前的数据为空，表示此次修改为新增数据
                    if (null == oldProfitConfInfos || oldProfitConfInfos.size() <= 0) {
                            for (ProfitConfInfo profitConfInfo : newProfitConfInfos) {
                                profitConfInfoService.save(profitConfInfo);

                                bizHisService.saveBizHisNew(profitConfInfo, profitConfInfo, user, org.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt,
                                        menuId, oprMenuName, profitConfInfo.getId(), null, null, null);
                            }
                    }
                    // 当前修改的数据为空或者不参与分润，清除分润配置信息
                    if ("0".equals(entity.getIsProfitFlag()) || newProfitConfInfos.size() <= 0) {
                        List<ProfitConfInfo> dbProfitConfInfoList = profitConfInfoService.findByBizCode(entity.getPlatMchntNo());
                        if (null != dbProfitConfInfoList && dbProfitConfInfoList.size() > 0) {
                            profitConfInfoService.delete(dbProfitConfInfoList);
                        }
                    }
                    // 比对新旧对象差异*/

                    // 处理旧分润信息
                    expProfit = profitConfInfoService.findByBizCode(entity.getPlatMchntNo());
                    //原分润信息 全部设置为到期
                    for (ProfitConfInfo p : expProfit) {
                        profitConfInfoService.getBaseMapper().deleteById(p.getId());
                    }

                    //分润信息处理


                    //保存新的分润信息
                    for (ProfitConfInfo p : saveProfit) {
                        p.setInstId(org.getInstId());
                        p.setProfitType("02");
                        p.setBizCode(entity.getPlatMchntNo());
                        p.setProfitEffectiveDate(nowDate);
                        p.setProfitExpiryDate(BusinessContainer.doomsday);
                        p.setProfitStatus(entity.getPlatMchntStatus());
                        p.setAuditStatus(entity.getAuditStatus());
                        p.setLastAuditId(user.getId());
                        p.setLastAuditTime(lastUpddt);
                        // 生成 分润配置唯一标识
                        p.setProfitPrimaryKey(genProfitPrimaryKey(p));
                        profitConfInfoService.save(p);

                        bizHisService.saveBizHisNew(p, p, user, org.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt,
                                menuId, oprMenuName, p.getId(), null, null, null);
                    }
                }
            }
        }
        // 停用，启用，注销
        if (PageOptFlagEnum.OPT_FLAG_STOP.getType().equals(optFlag)
                || PageOptFlagEnum.OPT_FLAG_USE.getType().equals(optFlag)
                || PageOptFlagEnum.OPT_FLAG_CANCEL.getType().equals(optFlag)) {
            String id = entity.getId();
            if (Common.isBlank(id)) {
                log.error("请求参数(id)异常!");
                return OperationResult.buildFailureResult("请求参数(id)异常!", result);
            }
            UpmpBPlatMchntInfo dbPlatMchntInfo = this.getById(id);
            if (Common.isBlank(dbPlatMchntInfo)) {
                log.error("根据id没有找到指定数据！");
                return OperationResult.buildFailureResult("根据id没有找到指定数据！", result);
            }

            UpmpBPlatMchntInfo UpmpBPlatMchntInfo = new UpmpBPlatMchntInfo();
            BeanUtils.copyProperties(dbPlatMchntInfo, UpmpBPlatMchntInfo);

            UpmpPrivilegeCheck privilegeCheck = new UpmpPrivilegeCheck();
            String bizOpr = "";
            if (PageOptFlagEnum.OPT_FLAG_STOP.getType().equals(optFlag)) {
                bizOpr = BizOprEnum.OPR_STOP.getType();
                privilegeCheck = upmpPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(user.getInstId(), "platMchnt:stop");
                if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                    UpmpBPlatMchntInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_STOP_CHECKING.getType());
                } else {
                    UpmpBPlatMchntInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_STOP_PASS.getType());
                    UpmpBPlatMchntInfo.setPlatMchntStatus(BizDataStatusEnum.STATUS_STOPED.getType());
                }
                UpmpBPlatMchntInfo.setStopReason(entity.getStopReason());
            } else if (PageOptFlagEnum.OPT_FLAG_USE.getType().equals(optFlag)) {

                bizOpr = BizOprEnum.OPR_USE.getType();
                privilegeCheck = upmpPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(user.getInstId(), "platMchnt:use");
                if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                    UpmpBPlatMchntInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_USE_CHECKING.getType());
                } else {
                    UpmpBPlatMchntInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_USE_PASS.getType());
                    UpmpBPlatMchntInfo.setPlatMchntStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
                }
            } else if (PageOptFlagEnum.OPT_FLAG_CANCEL.getType().equals(optFlag)) {

                bizOpr = BizOprEnum.OPR_CANCEL.getType();
                privilegeCheck = upmpPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(user.getInstId(), "platMchnt:delete");
                if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                    UpmpBPlatMchntInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_CANCEL_CHECKING.getType());
                } else {
                    UpmpBPlatMchntInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_CANCEL_PASS.getType());
                    UpmpBPlatMchntInfo.setPlatMchntStatus(BizDataStatusEnum.STATUS_CANCELED.getType());
                }
            }
            UpmpBPlatMchntInfo.setCancelReason(entity.getCancelReason());
            UpmpBPlatMchntInfo.setLastOprId(user.getId());
            UpmpBPlatMchntInfo.setLastUpdateTime(lastUpddt);

            this.saveOrUpdate(UpmpBPlatMchntInfo);

            if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                //检查临时表是否有数据，如果没用则新增
                bizTmpService.saveBizTmpDtl(UpmpBPlatMchntInfo, user, org.getInstId(), bizOpr, lastUpddt
                        , menuId, oprMenuName, UpmpBPlatMchntInfo.getPlatMchntStatus(), UpmpBPlatMchntInfo.getAuditStatus(), UpmpBPlatMchntInfo.getId(), webNextUrl, "N", "", null, null, null);
            } else {
                //历史表新增
                bizHisService.saveBizHisNew(UpmpBPlatMchntInfo, dbPlatMchntInfo, user, org.getInstId(), bizOpr, lastUpddt
                        , menuId, oprMenuName, UpmpBPlatMchntInfo.getId(), null, null, null);
            }
            result.put("id", UpmpBPlatMchntInfo.getId());
            return OperationResult.buildSuccessResult("数据保存处理完成", result);
        }

        result.put("id", entity.getId());
        return OperationResult.buildSuccessResult("数据保存处理完成", result);
    }

    @Override
    @Transactional(value = "transactionManager")
    public OperationResult chkData(String menuId, String oprMenuName, UpmpBPlatMchntInfo entity, HttpServletRequest request, String webNextUrl) throws RedpException {
        java.util.Map<String, Object> result = com.google.common.collect.Maps.newHashMap();
        String id = entity.getId();
        if (Common.isBlank(id)) {
            log.error("请求参数(id)异常!");
            return OperationResult.buildFailureResult("请求参数(id)异常!", result);
        }
        String opt = request.getParameter("optFlag");
        if (Common.isBlank(opt)) {
            log.error("请求参数(opt)异常!");
            return OperationResult.buildFailureResult("请求参数(opt)异常!", result);
        }
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        UpmpOrganization org = organizationService.getOrgByCode(user.getOrgCode(), user.getInstId());

        SimpleDateFormat fmtdt = new SimpleDateFormat("yyyyMMddHHmmss");
        String lastUpddt = fmtdt.format(new Date());
        entity.setLastOprId(user.getId());
        entity.setLastUpdateTime(lastUpddt);

        // 1、组装平台商户实体类对象
        // 1.1、获取临时表平台商户的数据并转换成实体对象
        BizTmp tmp = bizTmpService.getById(id);
        if (Common.isBlank(tmp)) {
            log.error("根据id没有找到指定临时表数据！");
            return OperationResult.buildFailureResult("根据id没有找到指定临时表数据！", result);
        }
        String bizdata = "";
        if (null != tmp.getBizData1()) {
            bizdata += tmp.getBizData1();
        }
        if (null != tmp.getBizData2()) {
            bizdata += tmp.getBizData2();
        }
        if (null != tmp.getBizData3()) {
            bizdata += tmp.getBizData3();
        }
        // 1.2、平台商户临时表数据
        UpmpBPlatMchntInfo platMchntInfoNew = JSON.parseObject(bizdata, UpmpBPlatMchntInfo.class);
        // 1.3、平台商户正式表数据
        UpmpBPlatMchntInfo UpmpBPlatMchntInfo = this.getById(id);
        // 1.3、备份平台商户正式表数据
        UpmpBPlatMchntInfo platMchntInfoOld = new UpmpBPlatMchntInfo();
        BeanUtils.copyProperties(UpmpBPlatMchntInfo, platMchntInfoOld);

        if (Common.isBlank(UpmpBPlatMchntInfo) && !BizOprEnum.OPR_ADD.equals(tmp.getBizOpr())) {
            log.error("根据id没有找到指定数据！");
            return OperationResult.buildFailureResult("根据id没有找到指定数据！", result);
        }
        // 2、组装微信商户实体类对象
        // 2.1、微信商户正式表数据
        WechatMchntInfo wechatMchntInfo = bWechatMchntInfoService.getBWechatMchntInfoByMchntNo(UpmpBPlatMchntInfo.getPlatMchntNo(),UpmpBPlatMchntInfo.getInstId());
        // 微信商户临时表数据
        WechatMchntInfo wechatMchntInfoNew = null;
        List<WechatMchntInfo> bWechatMchntInfos = bizTmpService.getBizTmpByInstIdAndMasterKeyAndEname(entity.getInstId(), WechatMchntInfo.class, entity.getId());
        if (null != bWechatMchntInfos && bWechatMchntInfos.size() > 0) {
            wechatMchntInfoNew = bWechatMchntInfos.get(0);
        }
        // 备份微信商户正式表数据
        WechatMchntInfo wechatMchntInfoOld = null;
        if (null != wechatMchntInfo) {
            wechatMchntInfoOld = new WechatMchntInfo();
            BeanUtils.copyProperties(wechatMchntInfo, wechatMchntInfoOld);
        }
        // 3、组装分润配置实体类对象
        List<ProfitConfInfo> profitConfInfos = profitConfInfoService.findByBizCode(entity.getPlatMchntNo());
        // 3.1、分润配置临时表数据
        List<ProfitConfInfo> profitConfInfosNew = bizTmpService.getBizTmpByInstIdAndMasterKeyAndEname(UpmpBPlatMchntInfo.getInstId(), ProfitConfInfo.class, UpmpBPlatMchntInfo.getId());
        // 3.2、备份分润配置正式表数据
        List<String> profitConfInfosOld = new ArrayList<>();
        for (ProfitConfInfo profitConfInfo : profitConfInfos) {
            ProfitConfInfo profitConfInfoOld = new ProfitConfInfo();
            BeanUtils.copyProperties(profitConfInfo, profitConfInfoOld);
            profitConfInfosOld.add(profitConfInfoOld.getId());
        }

        //
        if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
            // 审批通过将临时表数据更新到正式表
            BeanUtils.copyProperties(platMchntInfoNew, UpmpBPlatMchntInfo);
            // 微信商户信息处理

            // 微信商户临时表存在数据情况
            if (null != wechatMchntInfoNew) {
                // 微信商户正式表不存在数据情况
                if (null == wechatMchntInfo) {
                    wechatMchntInfo = new WechatMchntInfo();
                }
                BeanUtils.copyProperties(wechatMchntInfoNew, wechatMchntInfo);
            } else { // 微信商户临时表不存在数据情况

                // 微信商户正式表存在数据情况
                if (null != wechatMchntInfo) {
                    wechatMchntInfo = null;
                }
            }
            // 分润配置处理
            profitConfInfos.clear();
            for (ProfitConfInfo profitConfInfoNew : profitConfInfosNew) {
                ProfitConfInfo profitConfInfo = new ProfitConfInfo();
                BeanUtils.copyProperties(profitConfInfoNew, profitConfInfo);
                profitConfInfos.add(profitConfInfo);
            }
        } else {
            String approvalRefuseReason = request.getParameter("approvalRefuseReason");
            UpmpBPlatMchntInfo.setAuditRefuseReason(approvalRefuseReason);
        }

        String bizOpr = "";
        if (BizDataAuditStatusEnum.AUDIT_STATUS_ADD_CHECKING.getType().equals(UpmpBPlatMchntInfo.getAuditStatus())) {
            if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                UpmpBPlatMchntInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_PASS.getType());
                UpmpBPlatMchntInfo.setPlatMchntStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
            } else {
                UpmpBPlatMchntInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_REJECT.getType());
            }
            bizOpr = BizOprEnum.OPR_ADD.getType();
        } else if (BizDataAuditStatusEnum.AUDIT_STATUS_CANCEL_CHECKING.getType().equals(UpmpBPlatMchntInfo.getAuditStatus())) {
            if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                UpmpBPlatMchntInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_CANCEL_PASS.getType());
                UpmpBPlatMchntInfo.setPlatMchntStatus(BizDataStatusEnum.STATUS_CANCELED.getType());
            } else {
                UpmpBPlatMchntInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_CANCEL_REJECT.getType());
            }
            bizOpr = BizOprEnum.OPR_CANCEL.getType();
        } else if (BizDataAuditStatusEnum.AUDIT_STATUS_STOP_CHECKING.getType().equals(UpmpBPlatMchntInfo.getAuditStatus())) {
            if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                UpmpBPlatMchntInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_STOP_PASS.getType());
                UpmpBPlatMchntInfo.setPlatMchntStatus(BizDataStatusEnum.STATUS_STOPED.getType());
            } else {
                UpmpBPlatMchntInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_STOP_REJECT.getType());
            }
            bizOpr = BizOprEnum.OPR_STOP.getType();
        } else if (BizDataAuditStatusEnum.AUDIT_STATUS_USE_CHECKING.getType().equals(UpmpBPlatMchntInfo.getAuditStatus())) {
            if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                UpmpBPlatMchntInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_USE_PASS.getType());
                UpmpBPlatMchntInfo.setPlatMchntStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
            } else {
                UpmpBPlatMchntInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_USE_REJECT.getType());
            }
            bizOpr = BizOprEnum.OPR_USE.getType();
        } else if (BizDataAuditStatusEnum.AUDIT_STATUS_UPD_CHECKING.getType().equals(UpmpBPlatMchntInfo.getAuditStatus())) {
            if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                UpmpBPlatMchntInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_PASS.getType());
                UpmpBPlatMchntInfo.setPlatMchntStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
            } else {
                UpmpBPlatMchntInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_REJECT.getType());
            }
            bizOpr = BizOprEnum.OPR_UPDATE.getType();
        }

        // 状态赋值完成后，入库正式表
        this.saveOrUpdate(UpmpBPlatMchntInfo);
        // 微信商户信息处理
        if (null != wechatMchntInfo) {
            wechatMchntInfo.setAuditStatus(UpmpBPlatMchntInfo.getAuditStatus());
            bWechatMchntInfoService.save(wechatMchntInfo);
        } else {
            // 微信商户信息对象为空，删除正式表数据
            if (null != wechatMchntInfoOld) {
                bWechatMchntInfoService.getBaseMapper().deleteById(wechatMchntInfoOld.getId());
            }
        }
        // 分润配置处理
        if (profitConfInfosOld.size() > 0 && !PageOptFlagEnum.OPT_FLAG_REJECT.getType().equals(opt)) {
            // 正式表先删除
            profitConfInfoService.getBaseMapper().deleteBatchIds(profitConfInfosOld);
        }
        for (ProfitConfInfo profitConfInfo : profitConfInfos) {
            profitConfInfo.setProfitStatus(UpmpBPlatMchntInfo.getPlatMchntStatus());
            profitConfInfo.setAuditStatus(UpmpBPlatMchntInfo.getAuditStatus());
            profitConfInfoService.save(profitConfInfo);
        }
        //
        if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
            //审批通过将正式表更新到历史表
            bizHisService.saveBizHisNew(UpmpBPlatMchntInfo, platMchntInfoOld, user, org.getInstId(), bizOpr, lastUpddt, menuId, oprMenuName, UpmpBPlatMchntInfo.getId(), null, null, null);
            // 微信商户信息处理
            if (null != wechatMchntInfo) {
                if (null == wechatMchntInfoOld) {
                    wechatMchntInfoOld = new WechatMchntInfo();
                    BeanUtils.copyProperties(wechatMchntInfo, wechatMchntInfoOld);
                }
                bizHisService.saveBizHisNew(wechatMchntInfo, wechatMchntInfoOld, user, org.getInstId(), bizOpr, lastUpddt, menuId, oprMenuName, wechatMchntInfo.getId(), null, null, null);
            } else {
                if (null != wechatMchntInfoOld) {
                    bizHisService.saveBizHisNew(wechatMchntInfoOld, wechatMchntInfoOld, user, org.getInstId(), BizOprEnum.OPR_DELETE.getType(), lastUpddt, menuId, oprMenuName, wechatMchntInfoOld.getId(), null, null, null);
                }
            }
            // 分润配置处理;无法与old对象对比
            for (ProfitConfInfo profitConfInfo : profitConfInfos) {
                bizHisService.saveBizHisNew(profitConfInfo, profitConfInfo, user, org.getInstId(), bizOpr, lastUpddt, menuId, oprMenuName, profitConfInfo.getId(), null, null, null);
            }
            // 判断是否需要向微信进件，调用第三方进件接口进件
            if (null != wechatMchntInfo && "1".equals(UpmpBPlatMchntInfo.getIsWechatEntryFlag())) {
               /* log.info("开始第三方进件！");
                InstMchntRegisterRequest req = new InstMchntRegisterRequest();
                req.setMchntNo(UpmpBPlatMchntInfo.getPlatMchntNo());*/
                String oprType = "0";
                if (bizOpr.equals(BizOprEnum.OPR_ADD.getType())) {
                    oprType = "0";
                } else if (bizOpr.equals(BizOprEnum.OPR_UPDATE.getType())) {
                    oprType = "1";
                }
                //进件状态为空或者失败，且微信商户号为空时是入驻
                if ((Common.isBlank(wechatMchntInfo.getWechatEntryFlag()) || "02".equals(wechatMchntInfo.getWechatEntryFlag())) && Common.isBlank(wechatMchntInfo.getWechatMchntNo())) {
                    oprType = "0";
                }
               /* req.setChannelType(entity.getChannelType());
                req.setChannelFlag("01");
                req.setWechatAppid(wechatMchntInfo.getAppId());
                req.setWechatMiniAppid(wechatMchntInfo.getMiniAppId());
                req.setUserId(user.getId());
                req.setMchntBizFlag("01");
                req.setOprType(oprType);
                bMchntBaseInfoService.thirdEntry(UpmpBPlatMchntInfo.getInstId(), req, bompThirdMchntEntryService, bMchntBaseInfoService.genMerOrder(user.getInstId()));*/
                result.put("mchntNo", UpmpBPlatMchntInfo.getPlatMchntNo());
                result.put("channelType", entity.getChannelType());
                result.put("appId", wechatMchntInfo.getAppId());
                result.put("miniAppId", wechatMchntInfo.getMiniAppId());
                result.put("oprType", oprType);
            }
        } else if (PageOptFlagEnum.OPT_FLAG_REJECT.getType().equals(opt)) {
            // 处理审核退回,profitConfInfosNew和profitConfInfos对象不一致数据的删除
            Map<String, Boolean> profiltConfInfoMap = new HashMap<>();
            for (ProfitConfInfo profitConfInfo : profitConfInfos) {
                profiltConfInfoMap.put(profitConfInfo.getId(), true);
            }
            for (ProfitConfInfo profitConfInfo : profitConfInfosNew) {
                if (!profiltConfInfoMap.containsKey(profitConfInfo.getId())) {
                    BizTmp bizTmp = bizTmpService.getById(profitConfInfo.getId());
                    if (null != bizTmp) {
                        bizTmpService.getBaseMapper().deleteById(bizTmp.getRealId());
                    }
                }
            }
        }
        // 修改临时表的审核状态等字段
        bizTmpService.saveBizTmpDtl(UpmpBPlatMchntInfo, user, org.getInstId(), bizOpr, lastUpddt, menuId, oprMenuName, UpmpBPlatMchntInfo.getPlatMchntStatus(), UpmpBPlatMchntInfo.getAuditStatus(), UpmpBPlatMchntInfo.getId(), webNextUrl, "N", "", null, null, null);
        // 微信商户信息处理
        if (null != wechatMchntInfo) {
            bizTmpService.saveBizTmpDtl(wechatMchntInfo, user, org.getInstId(), bizOpr, lastUpddt, menuId, oprMenuName, UpmpBPlatMchntInfo.getPlatMchntStatus(), wechatMchntInfo.getAuditStatus(), wechatMchntInfo.getId(), webNextUrl, "Y", UpmpBPlatMchntInfo.getId(), null, null, null);
        } else {
            // 微信商户表对象为空，删除临时表数据
            if (null != bWechatMchntInfos) {
                for (WechatMchntInfo WechatMchntInfo : bWechatMchntInfos) {
                    BizTmp bizTmp = bizTmpService.getById(WechatMchntInfo.getId());
                    bizTmpService.getBaseMapper().deleteById(bizTmp.getRealId());
                }
            }
        }
        // 分润配置处理
        for (ProfitConfInfo profitConfInfo : profitConfInfos) {
            bizTmpService.saveBizTmpDtl(profitConfInfo, user, org.getInstId(), bizOpr, lastUpddt, menuId, oprMenuName, UpmpBPlatMchntInfo.getPlatMchntStatus(), profitConfInfo.getAuditStatus(), profitConfInfo.getId(), webNextUrl, "Y", UpmpBPlatMchntInfo.getId(), null, null, null);
        }

        result.put("id", UpmpBPlatMchntInfo.getId());

        return OperationResult.buildSuccessResult("数据保存处理完成", result);
    }
    private WechatMchntInfo getBWechatMchntInfo(UpmpBPlatMchntInfo platMchntInfo) throws RedpException {
        WechatMchntInfo wechatMchntInfo = new WechatMchntInfo();
        wechatMchntInfo.setInstId(platMchntInfo.getInstId());
        wechatMchntInfo.setMchntNo(platMchntInfo.getPlatMchntNo());
        wechatMchntInfo.setWechatMchntType(platMchntInfo.getEnterRegisterType());
        wechatMchntInfo.setWechatEntryFlag("00");
        wechatMchntInfo.setRecordStatus("Y");
        wechatMchntInfo.setAuditStatus(platMchntInfo.getAuditStatus());
        wechatMchntInfo.setOprId(platMchntInfo.getOprId());
        wechatMchntInfo.setCreateTime(platMchntInfo.getCreateTime());
        String publicPrivateFlag="";
        if("03".equals(platMchntInfo.getEnterRegisterType())){
            publicPrivateFlag = "01";
        }else if("01".equals(platMchntInfo.getEnterRegisterType())||"02".equals(platMchntInfo.getEnterRegisterType())){
            publicPrivateFlag = "02";
        }else if("04".equals(platMchntInfo.getEnterRegisterType())){
            publicPrivateFlag = "03";
        }else if("99".equals(platMchntInfo.getEnterRegisterType())){
            publicPrivateFlag = "04";
        }
        // 根据行业类别，获取微信一级二级类目
        IndustryMapInfo industryMap = industryMapService.findIndustryMap(platMchntInfo.getIndustryType(), "WXZF",publicPrivateFlag);
        if(industryMap == null){
            industryMap = industryMapService.findIndustryMap(platMchntInfo.getIndustryType(), "WXZF","01");
        }
        if (null == industryMap) {
            log.error("根据行业类别查询微信二级类目失败！");
            throw new RedpException("根据行业类别查询微信二级类目失败！");
        }
        String wechatSecondCategory = industryMap.getDestCatalogCd();
        /*WctSec wctSec = wctSecService.getByUk(wechatSecondCategory);
        if (null == wctSec) {
            log.error("查询微信二级类目失败！");
            throw new RedpException("查询微信二级类目失败！");
        }*/
//        wechatMchntInfo.setWechatFirstCategory(wctSec.getWctUpNo());
        wechatMchntInfo.setWechatSecondCategory(wechatSecondCategory);

        wechatMchntInfo.setDstChannelType(platMchntInfo.getChannelType());
        wechatMchntInfo.setAppId(platMchntInfo.getAppId());
        wechatMchntInfo.setAppSecretKey(platMchntInfo.getAppSecretKey());
        wechatMchntInfo.setMiniAppId(platMchntInfo.getMiniAppId());
        wechatMchntInfo.setMiniSecretKey(platMchntInfo.getMiniSecretKey());
        return wechatMchntInfo;
    }
}
